package com.wjw.java.collection.list_;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

/**
 * 集合练习：使用冒泡排序按数的价格从低到高排序
 */
public class ListExercise {
    public static void main(String[] args) {
        List list = new ArrayList();
        //LinkedList list = new LinkedList();
        //Vector list = new Vector();

        list.add(new Book("Java",99.99));
        list.add(new Book("HTML",79.99));
        list.add(new Book("CSS",69.99));
        list.add(new Book("JavaScript",199.99));
        list.add(new Book("Oracle",299.99));
        list.add(new Book("MySql",188.99));

        priceASC(list);
        for (Object o : list) {
            System.out.println(o);
        }
        System.out.println("-----------------------------------------");
        priceDESC(list);
        for (Object o : list) {
            System.out.println(o);
        }
    }

    /**
     * 按照价格升序排序
     * @param list
     */
    public static void priceASC(List list){
        int size = list.size();
        for (int i = 0; i < size - 1; i++) {
            for(int j = 0; j < size - 1 - i; j++){
                //取出当前索引和下一个索引的元素
                Book b1 = (Book) list.get(j);
                Book b2 = (Book) list.get(j+1);
                //前面的价格比后面价格贵,就交换位置
                if(b1.getPrice() > b2.getPrice()){
                    list.set(j,b2);
                    list.set(j+1,b1);
                }
            }
        }//for
    }

    /**
     * 按照价格降序排序
     * @param list
     */
    public static void priceDESC(List list){
        int size = list.size();
        for (int i = 0; i < size - 1; i++) {
            for(int j = 0; j < size - 1 - i; j++){
                //取出当前索引和下一个索引的元素
                Book b1 = (Book) list.get(j);
                Book b2 = (Book) list.get(j+1);
                //前面的价格比后面价格贵,就交换位置
                if(b1.getPrice() < b2.getPrice()){
                    list.set(j,b2);
                    list.set(j+1,b1);
                }
            }
        }//for
    }
}

class Book{
    String name;
    double price;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return this.price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public Book() {
    }

    public Book(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}